package com.example.lenovo.weiyi;

import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.com.ruanmeng.demon.ChooseAnswerM;
import com.com.ruanmeng.demon.JinJiListM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.Params;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.view.CustomGridView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

/**
 * 禁忌症调查
 */
public class JinJiSurveyActivity extends BaseActivity {

    @BindView(R.id.gv_dc)
    CustomGridView gvDc;
    @BindView(R.id.bt_surveyok)
    Button btSurveyok;
    ArrayList<JinJiListM.RowsBean> Temp_list = new ArrayList<>();
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.ed_jj_mubiao)
    EditText edJjMubiao;
    @BindView(R.id.iv_jj_mb)
    ImageView ivJjMb;
    private JinJiAdapter jjadapter;
    private String null_position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jin_ji_survey);
        ButterKnife.bind(this);
        ChangLayTitle("调查");
        AddActivity(this);
        LayBack();
        init();
        getData();
    }

    public void init() {
        jjadapter = new JinJiAdapter(Temp_list);
        gvDc.setAdapter(jjadapter);
        edJjMubiao.setText(Params.cureTarget);
        edJjMubiao.addTextChangedListener(this);
    }

    @Override
    public void onTextChanged(CharSequence s, int i, int i1, int i2) {
        super.onTextChanged(s, i, i1, i2);
        if (s.length() > 0) {
            ivJjMb.setVisibility(View.VISIBLE);
        } else {
            ivJjMb.setVisibility(View.GONE);
        }
    }

    /**
     * 获取禁忌症列表
     */
    public void getData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.JinJIList, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(JinJiSurveyActivity.this, "uid"));
        mRequest.add("assessId", getIntent().getStringExtra("id"));
        // 添加到请求队列
        CallServer.getRequestInstance().add(JinJiSurveyActivity.this, 0, mRequest,
                new CustomHttpListener(JinJiSurveyActivity.this, true, JinJiListM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        JinJiListM model = ((JinJiListM) data);
                        Temp_list.addAll(model.getRows());
                        jjadapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, true);
    }

    /**
     * 提交
     */
    public void getSaveData(String ids, String names) {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.JinJISave, Const.POST);
        mRequest.addHeader("token", PreferencesUtils.getString(JinJiSurveyActivity.this, "uid"));
        mRequest.add("assessId", getIntent().getStringExtra("id"));
        mRequest.add("contrtions", names);
        mRequest.add("contrtionsId", ids);
        mRequest.add("cureTarget", edJjMubiao.getText().toString());
        // 添加到请求队列
        CallServer.getRequestInstance().add(JinJiSurveyActivity.this, 0, mRequest,
                new CustomHttpListener(JinJiSurveyActivity.this, true, ChooseAnswerM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        ChooseAnswerM model = ((ChooseAnswerM) data);
                        jjadapter.notifyDataSetChanged();
                        Params.CreateKFPD = 1;
                        clearActivity();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, true);
    }

    /**
     * 禁忌症
     */
    class JinJiAdapter extends BaseAdapter {
        private List<JinJiListM.RowsBean> list;

        public JinJiAdapter(List<JinJiListM.RowsBean> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View v, ViewGroup parent) {
            v = getLayoutInflater().inflate(R.layout.item_choosejinji, null);
            LinearLayout li_choose_jj = (LinearLayout) v.findViewById(R.id.li_choose_jj);
            TextView name = (TextView) v.findViewById(R.id.tv_choosejj_jinjiname);
            final CheckBox cb_choose_jj = (CheckBox) v.findViewById(R.id.cb_choose_jj);
            name.setText(list.get(position).getContrtionName());
            if (list.get(position).getIsSelect() == 1) {
                cb_choose_jj.setChecked(true);
            } else {
                cb_choose_jj.setChecked(false);
            }
            for (int i = 0; i < Temp_list.size(); i++) {
                if (("无").equals(list.get(i).getContrtionName())) {
                    null_position = i + "";//无的位置
                }
            }
            li_choose_jj.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (cb_choose_jj.isChecked() == true) {
                        cb_choose_jj.setChecked(false);
                        Temp_list.get(position).setIsSelect(0);
                    } else {
                        //选无的时候  别的选项要清除
                        if (!TextUtils.isEmpty(null_position) && position == Integer.parseInt(null_position)) {
                            for (int i = 0; i < Temp_list.size(); i++) {
                                Temp_list.get(i).setIsSelect(0);
                            }
                        } else if (!TextUtils.isEmpty(null_position)) {
                            Temp_list.get(Integer.parseInt(null_position)).setIsSelect(0);
                        }
                        cb_choose_jj.setChecked(true);
                        Temp_list.get(position).setIsSelect(1);
                    }
                    jjadapter.notifyDataSetChanged();
                }
            });
            return v;
        }

    }

    public void doClick(View v) {
        switch (v.getId()) {
            case R.id.bt_surveyok://完成并提交
                int a = 0;
                for (int i = 0; i < Temp_list.size(); i++) {
                    if (Temp_list.get(i).getIsSelect() == 1) {
                        a = 1;
                    }
                }
                if (a == 0) {
                    CommonUtil.showToask(JinJiSurveyActivity.this, "请选择禁忌症！");
                    return;
                }
                /*if (TextUtils.isEmpty(edJjMubiao.getText().toString())) {
                    CommonUtil.showToask(JinJiSurveyActivity.this, "请输入您期望达到的目标！");
                    return;
                }*/
                ShowTiShi();
                break;
            case R.id.iv_jj_mb:
                edJjMubiao.setText("");
                break;
        }
    }

    /**
     * 关于弹窗提示
     */
    public void ShowTiShi() {
        // 加载布局
        LayoutInflater inflater = LayoutInflater
                .from(JinJiSurveyActivity.this);
        View view = inflater.inflate(R.layout.pop_tijiao, null);
        TextView tv_backtosee = (TextView) view.findViewById(R.id.tv_cancle);
        TextView tv_pop_tj = (TextView) view.findViewById(R.id.tv_pop_tj);
        // 创建popupwindow对话框
        final PopupWindow pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);// 必须有，因为要获得焦点进行输入
        // 设置此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 点击其他除了popupwindow对话框的地方就可使popupwindow对话框消失
        pop.setOutsideTouchable(true);
//        pop.showAtLocation(liFr, Gravity.CENTER, 0, 0);// 显示位置以某控件为中心
        if (Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            viewLine.getLocationInWindow(a);
            pop.showAtLocation((JinJiSurveyActivity.this).getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + viewLine.getHeight());
        } else {
            pop.showAsDropDown(viewLine);
        }
        tv_backtosee.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
            }
        });
        tv_pop_tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //提交
                pop.dismiss();
                StringBuffer buffername = new StringBuffer("");
                StringBuffer bufferid = new StringBuffer("");
                for (int i = 0; i < Temp_list.size(); i++) {
                    if (Temp_list.get(i).getIsSelect() == 1) {
                        buffername.append(Temp_list.get(i).getContrtionName());
                        bufferid.append(Temp_list.get(i).getContrtionId());
                        if (i != Temp_list.size() - 1) {
                            buffername.append(",");
                            bufferid.append(",");
                        }
                    }
                }
                String names_str = buffername.toString();
                String ids_str = bufferid.toString();
                if (names_str.endsWith(",")) {
                    names_str = names_str.substring(0, names_str.length() - 1);
                    ids_str = ids_str.substring(0, ids_str.length() - 1);
                }
                getSaveData(ids_str, names_str);

            }
        });
    }

}
